package com.cheyun.netsalev3.view.stockquery

import android.os.Bundle
import android.util.Log
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.RecyclerView
import com.cheyun.netsalev3.R
import com.cheyun.netsalev3.adapter.MyPagedListAdapter
import com.cheyun.netsalev3.bean.StockParam
import com.cheyun.netsalev3.databinding.StockQueryListFragmentBinding
import com.cheyun.netsalev3.utils.BaseFragment
import com.cheyun.netsalev3.utils.InjectorUtils
import com.cheyun.netsalev3.utils.api.NetworkState
import com.cheyun.netsalev3.viewmodel.StockQueryListViewModel

class StockQueryListFragment: BaseFragment<StockQueryListFragmentBinding>() {
    private var state = ""
    var hashMap = HashMap<String, String>()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {
            state = it.getString("state")
            it.getSerializable("hashMap")?.apply {
                hashMap = this as HashMap<String, String>
            }

        }
    }

    override fun initContentView(): Int {
        return R.layout.stock_query_list_fragment
    }

    override fun initViewModel(): ViewModel? {
        if (state.isNotEmpty()) {
            hashMap["nkey"] = "index"
            hashMap["ckey"] = state
        }
        val factory = InjectorUtils.getStockQueryListViewModelFactory(hashMap)
        return ViewModelProviders.of(this, factory).get(StockQueryListViewModel::class.java)
    }

    private lateinit var adapter: MyPagedListAdapter<StockParam>

    override fun initView() {
        adapter = MyPagedListAdapter(R.layout.stock_query_list_item, binding.viewModel)
        var recyclerView = binding.root.findViewById<RecyclerView>(R.id.swipe_target)
        recyclerView.adapter = adapter
        binding.swipeRefreshLayout.setOnRefreshListener {
            binding.viewModel?.refresh()

        }
    }

    override fun initData() {
        binding.viewModel?.items?.observe(this, Observer { list ->
            list?.apply {
                adapter.submitList(list)
            }
        })
        binding.viewModel?.networkState?.observe(this, Observer {
            binding.swipeRefreshLayout.isRefreshing = it == NetworkState.LOADING
            adapter.setNetworkState(it)
        })
    }

    override fun lazyInit() {
        Log.i(TAG,"override lazyinit")
    }

    companion object {
        //        库存状态 1 => '在途',2 => '预定',3 => '在库',4 => '出库',5 => '配车',
        @JvmStatic
        fun newInstance(state: String, hashMap: HashMap<String, String>? = HashMap<String, String>()) =
                StockQueryListFragment().apply {
                    arguments = Bundle().apply {
                        putString("state", state)
                        putSerializable("hashMap", hashMap)
                    }
                }
    }


}
